import axios from "axios";

import { ElLoading } from "element-plus";

import Message from "./Message";
import router from '@/router';

const contentTypeForm = "application/x-www-form-urlencoded;charset=UTF-8";
const contentTypeJson = "application/json"

const instance = axios.create({
    baseURL: "/api",
    timeout: 10 * 1000,
})

let loading = null;
// 请求前过滤器
instance.interceptors.request.use((config) => {
    if (config.showLoading) {
        loading = ElLoading.service({
            lock: true,
            text: "加载中......",
            background: "rgba(0,0,0,0.7)"
        })
    }
    return config;
}, (error) => {
    if (error.config.showLoading && loading) {
        loading.close();
    }
    Message.error("请求发送失败")
    return Promise.reject("请求发送失败")
});

// 请求后过滤器
instance.interceptors.response.use(
    (response) => {
        const { showLoading, showError = true } = response.config;
        const { code, info } = response.data;

        if (showLoading && loading) {
            loading.close();
        }

        if (code == 200) {
            return response.data;
        } else if (code == 901) {
            router.push('/login')
            return Promise.reject({ showError: true, msg: '登录超时' });
        } else {
            if (typeof errorCallback == 'function') {
                errorCallback(response.data);
            }
            return Promise.reject({ showError: showError, msg: info || '未知错误' });
        }
    },
    (error) => {
        const { showLoading } = error.config || {};

        if (showLoading && loading) {
            loading.close();
        }

        return Promise.reject({ showError: true, msg: '网络异常' });
    }
);


const request = (config) => {
    const { url, params, dataType, showLoading = true, errorCallback, showError = true } = config
    let contentType = contentTypeForm;
    let formData = new FormData();
    for (let key in params) {
        formData.append(key, params[key] == undefined ? "" : params[key])
    }
    if (dataType != null && dataType === "json") {
        contentType = contentTypeJson
    }
    let headers = {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest',
    }
    return instance.post(url, formData, {
        headers: headers,
        showLoading: showLoading,
        errorCallback: errorCallback,
        showError: showError
    }).catch(error => {
        if (error.showError) {
            Message.error(error.msg)
        }
        if (errorCallback) {
            errorCallback(error);
        }
        return null
    })
}

export default request;